package com.open.capacity.user.service.impl;

import com.open.capacity.commons.Result;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.user.dao.SysUserRelationDao;
import com.open.capacity.user.model.SysPost;
import com.open.capacity.user.model.SysUserRelation;
import com.open.capacity.user.service.SysPostService;
import com.open.capacity.user.service.SysUserRelationService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.user.vo.SysUserRelationVo;
import com.open.capacity.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Service
public class SysUserRelationServiceImpl implements SysUserRelationService {

    @Autowired
    private SysUserRelationDao sysUserRelationDao;

    @Autowired
    private SysPostService postService;

    @Autowired
    private SysUserService sysUserService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SysUserRelation sysUserRelation) {
        sysUserRelation.setCreateTime(new Date());

        sysUserRelationDao.save(sysUserRelation);
        log.info("保存用户关联：{}", sysUserRelation);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByObjectId(String objectId) {

        sysUserRelationDao.deleteByObjectId(objectId);

        log.info("删除用户关联：{}", objectId);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByUserId(String userId, String objectType) {

        sysUserRelationDao.deleteByUserId(userId, objectType);

        log.info("删除用户关联：{}", userId);
    }

    @Override
    public List<SysUserRelation> findByObjectId(String objectId) {
        return sysUserRelationDao.findByObjectId(objectId);
    }

    @Override
    public List<SysUserRelation> findByObjectIds(List<String> objectIds) {
        return sysUserRelationDao.findByObjectIds(objectIds);
    }

    @Override
    public List<SysUserRelation> findByUserId(String userId) {
        return sysUserRelationDao.findByUserId(userId);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result saveOrUpdate(SysUserRelationVo sysUserRelation) {

        List<SysUserRelation> origList = sysUserRelationDao.findByObjectId(sysUserRelation.getObjectId());
        if (!CollectionUtils.isEmpty(origList)) {
            List<String> deleteUserIds = origList.stream().map(SysUserRelation::getUserId).filter(item -> !sysUserRelation.getUserIds().contains(item)).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(deleteUserIds)) {
                sysUserRelationDao.deleteByIds(sysUserRelation.getObjectId(), deleteUserIds);
            }
        }

        Date now = new Date();

        if (!CollectionUtils.isEmpty(sysUserRelation.getUserIds())) {

            List<String> addUserIds = sysUserRelation.getUserIds().stream().filter(item -> !origList.stream().map(SysUserRelation::getUserId).collect(Collectors.toList()).contains(item)).collect(Collectors.toList());
            addUserIds.forEach(u -> {
                SysUserRelation model = new SysUserRelation();
                model.setId(UUIDUtils.getOriginalUUIDWithoutBar());
                model.setObjectType(sysUserRelation.getObjectType());
                model.setObjectId(sysUserRelation.getObjectId());
                model.setStatus(-1);
                model.setUserId(u);
                model.setCreateTime(now);
                sysUserRelationDao.save(model);
            });
        }

        return 1 > 0 ? Result.succeed("操作成功") : Result.failed("操作失败");
    }

    @Override
    public String getPostNames(String userId) {
        SysUser sysUser = sysUserService.findById(userId);
        Assert.notNull(sysUser, "用户不存在");
        List<SysUserRelation> objectList = sysUserRelationDao.findByUserId(userId);
        List<String> postIds = objectList.stream().filter(p -> p.getObjectType().equals("Post")).map(SysUserRelation::getObjectId).collect(Collectors.toList());
        String postNames = "";
        for (String p : postIds) {
            SysPost post = postService.findById(p);
            if (StringUtils.isNotEmpty(postNames)) {
                postNames = postNames + "、" + post.getName();
            } else {
                postNames = post.getName();
            }
        }
        if (StringUtils.isEmpty(postNames)) {
            SysPost defaultPost = postService.findDefault(sysUser.getCompanyId());
            if (defaultPost != null) {
                postNames = defaultPost.getName();
            }
        }
        return postNames;
    }
}
